package com.catl.swap.test;

import com.catl.swap.plc.master.Master;
import com.catl.swap.plc.master.ModbusTcpMaster;
import com.catl.swap.plc.master.Plc4jMaster;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;
import org.apache.plc4x.java.PlcDriverManager;
import org.apache.plc4x.java.opm.PlcEntityManager;
import org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @ClassName Config
 * @Date 2021/12/29 14:08
 * @Author 王东平
 */
@Configuration
public class Config {
    @Bean
    public Master master() throws ModbusInitException {
        IpParameters ipParameters = new IpParameters();
        ipParameters.setHost("127.0.0.1");
        ipParameters.setPort(502);
        ModbusTcpMaster modbusTcpMaster = new ModbusTcpMaster(ipParameters, true);
        modbusTcpMaster.setTimeout(5000);
        modbusTcpMaster.init();

        PlcDriverManager driverManager = new PooledPlcDriverManager();
        Plc4jMaster plc4JMaster = new Plc4jMaster();
        plc4JMaster.setTimeout(5000);
        plc4JMaster.setPort(502);
        plc4JMaster.setIp("127.0.0.1");
        plc4JMaster.setPlcDriverManager(driverManager);

        Master master = new Master();
        master.setPlc4jMaster(plc4JMaster);
        master.setModbus4jMaster(modbusTcpMaster);
        master.setType(2);
        return master;
    }
    @Bean
    public ModbusMaster modbusMaster(){
        IpParameters ipParameters = new IpParameters();
        ipParameters.setHost("127.0.0.1");
        ipParameters.setPort(502);
        ModbusTcpMaster master = new ModbusTcpMaster(ipParameters,true);
        master.setTimeout(5000);
        try {
            master.init();
        } catch (ModbusInitException e) {
            e.printStackTrace();
        }
        return master;
    }

    @Bean
    public PlcDriverManager plDriverManager()  {
        PlcDriverManager driverManager = new PooledPlcDriverManager();
        return driverManager;
    }

    @Bean
    public PlcEntityManager plcEntityManager(){
//        String connectionString = "modbus:tcp://127.0.0.1:502?request-timeout=5000&unit-identifier=1";
        PlcEntityManager plcEntityManager = new PlcEntityManager(plDriverManager());
        return plcEntityManager;
    }
}
